_collections.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. from __future__ import absolute_import
  2. try:
  3. from collections.abc import Mapping, MutableMapping
  4. except ImportError:
  5. from collections import Mapping, MutableMapping
  6. try:
  7. from threading import RLock
  8. except ImportError: # Platform-specific: No threads available
  9. class RLock:
  10. def __enter__(self):
  11. pass
  12. def __exit__(self, exc_type, exc_value, traceback):
  13. pass
  14. from collections import OrderedDict
  15. from .exceptions import InvalidHeader
  16. from .packages.six import iterkeys, itervalues, PY3
  17. __all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"]
  18. _Null = object()
  19. class RecentlyUsedContainer(MutableMapping):
  20. """
  21. Provides a thread-safe dict-like container which maintains up to
  22. ``maxsize`` keys while throwing away the least-recently-used keys beyond
  23. ``maxsize``.
  24. :param maxsize:
  25. Maximum number of recent elements to retain.
  26. :param dispose_func:
  27. Every time an item is evicted from the container,
  28. ``dispose_func(value)`` is called. Callback which will get called
  29. """
  30. ContainerCls = OrderedDict
  31. def __init__(self, maxsize=10, dispose_func=None):
  32. self._maxsize = maxsize
  33. self.dispose_func = dispose_func
  34. self._container = self.ContainerCls()
  35. self.lock = RLock()
  36. def __getitem__(self, key):
  37. # Re-insert the item, moving it to the end of the eviction line.
  38. with self.lock:
  39. item = self._container.pop(key)
  40. self._container[key] = item
  41. return item
  42. def __setitem__(self, key, value):
  43. evicted_value = _Null
  44. with self.lock:
  45. # Possibly evict the existing value of 'key'
  46. evicted_value = self._container.get(key, _Null)
  47. self._container[key] = value
  48. # If we didn't evict an existing value, we might have to evict the
  49. # least recently used item from the beginning of the container.
  50. if len(self._container) > self._maxsize:
  51. _key, evicted_value = self._container.popitem(last=False)
  52. if self.dispose_func and evicted_value is not _Null:
  53. self.dispose_func(evicted_value)
  54. def __delitem__(self, key):
  55. with self.lock:
  56. value = self._container.pop(key)
  57. if self.dispose_func:
  58. self.dispose_func(value)
  59. def __len__(self):
  60. with self.lock:
  61. return len(self._container)
  62. def __iter__(self):
  63. raise NotImplementedError(
  64. "Iteration over this class is unlikely to be threadsafe."
  65. )
  66. def clear(self):
  67. with self.lock:
  68. # Copy pointers to all values, then wipe the mapping
  69. values = list(itervalues(self._container))
  70. self._container.clear()
  71. if self.dispose_func:
  72. for value in values:
  73. self.dispose_func(value)
  74. def keys(self):
  75. with self.lock:
  76. return list(iterkeys(self._container))
  77. class HTTPHeaderDict(MutableMapping):
  78. """
  79. :param headers:
  80. An iterable of field-value pairs. Must not contain multiple field names
  81. when compared case-insensitively.
  82. :param kwargs:
  83. Additional field-value pairs to pass in to ``dict.update``.
  84. A ``dict`` like container for storing HTTP Headers.
  85. Field names are stored and compared case-insensitively in compliance with
  86. RFC 7230. Iteration provides the first case-sensitive key seen for each
  87. case-insensitive pair.
  88. Using ``__setitem__`` syntax overwrites fields that compare equal
  89. case-insensitively in order to maintain ``dict``'s api. For fields that
  90. compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``
  91. in a loop.
  92. If multiple fields that are equal case-insensitively are passed to the
  93. constructor or ``.update``, the behavior is undefined and some will be
  94. lost.
  95. >>> headers = HTTPHeaderDict()
  96. >>> headers.add('Set-Cookie', 'foo=bar')
  97. >>> headers.add('set-cookie', 'baz=quxx')
  98. >>> headers['content-length'] = '7'
  99. >>> headers['SET-cookie']
  100. 'foo=bar, baz=quxx'
  101. >>> headers['Content-Length']
  102. '7'
  103. """
  104. def __init__(self, headers=None, **kwargs):
  105. super(HTTPHeaderDict, self).__init__()
  106. self._container = OrderedDict()
  107. if headers is not None:
  108. if isinstance(headers, HTTPHeaderDict):
  109. self._copy_from(headers)
  110. else:
  111. self.extend(headers)
  112. if kwargs:
  113. self.extend(kwargs)
  114. def __setitem__(self, key, val):
  115. self._container[key.lower()] = [key, val]
  116. return self._container[key.lower()]
  117. def __getitem__(self, key):
  118. val = self._container[key.lower()]
  119. return ", ".join(val[1:])
  120. def __delitem__(self, key):
  121. del self._container[key.lower()]
  122. def __contains__(self, key):
  123. return key.lower() in self._container
  124. def __eq__(self, other):
  125. if not isinstance(other, Mapping) and not hasattr(other, "keys"):
  126. return False
  127. if not isinstance(other, type(self)):
  128. other = type(self)(other)
  129. return dict((k.lower(), v) for k, v in self.itermerged()) == dict(
  130. (k.lower(), v) for k, v in other.itermerged()
  131. )
  132. def __ne__(self, other):
  133. return not self.__eq__(other)
  134. if not PY3: # Python 2
  135. iterkeys = MutableMapping.iterkeys
  136. itervalues = MutableMapping.itervalues
  137. __marker = object()
  138. def __len__(self):
  139. return len(self._container)
  140. def __iter__(self):
  141. # Only provide the originally cased names
  142. for vals in self._container.values():
  143. yield vals[0]
  144. def pop(self, key, default=__marker):
  145. """D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  146. If key is not found, d is returned if given, otherwise KeyError is raised.
  147. """
  148. # Using the MutableMapping function directly fails due to the private marker.
  149. # Using ordinary dict.pop would expose the internal structures.
  150. # So let's reinvent the wheel.
  151. try:
  152. value = self[key]
  153. except KeyError:
  154. if default is self.__marker:
  155. raise
  156. return default
  157. else:
  158. del self[key]
  159. return value
  160. def discard(self, key):
  161. try:
  162. del self[key]
  163. except KeyError:
  164. pass
  165. def add(self, key, val):
  166. """Adds a (name, value) pair, doesn't overwrite the value if it already
  167. exists.
  168. >>> headers = HTTPHeaderDict(foo='bar')
  169. >>> headers.add('Foo', 'baz')
  170. >>> headers['foo']
  171. 'bar, baz'
  172. """
  173. key_lower = key.lower()
  174. new_vals = [key, val]
  175. # Keep the common case aka no item present as fast as possible
  176. vals = self._container.setdefault(key_lower, new_vals)
  177. if new_vals is not vals:
  178. vals.append(val)
  179. def extend(self, *args, **kwargs):
  180. """Generic import function for any type of header-like object.
  181. Adapted version of MutableMapping.update in order to insert items
  182. with self.add instead of self.__setitem__
  183. """
  184. if len(args) > 1:
  185. raise TypeError(
  186. "extend() takes at most 1 positional "
  187. "arguments ({0} given)".format(len(args))
  188. )
  189. other = args[0] if len(args) >= 1 else ()
  190. if isinstance(other, HTTPHeaderDict):
  191. for key, val in other.iteritems():
  192. self.add(key, val)
  193. elif isinstance(other, Mapping):
  194. for key in other:
  195. self.add(key, other[key])
  196. elif hasattr(other, "keys"):
  197. for key in other.keys():
  198. self.add(key, other[key])
  199. else:
  200. for key, value in other:
  201. self.add(key, value)
  202. for key, value in kwargs.items():
  203. self.add(key, value)
  204. def getlist(self, key, default=__marker):
  205. """Returns a list of all the values for the named field. Returns an
  206. empty list if the key doesn't exist."""
  207. try:
  208. vals = self._container[key.lower()]
  209. except KeyError:
  210. if default is self.__marker:
  211. return []
  212. return default
  213. else:
  214. return vals[1:]
  215. # Backwards compatibility for httplib
  216. getheaders = getlist
  217. getallmatchingheaders = getlist
  218. iget = getlist
  219. # Backwards compatibility for http.cookiejar
  220. get_all = getlist
  221. def __repr__(self):
  222. return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))
  223. def _copy_from(self, other):
  224. for key in other:
  225. val = other.getlist(key)
  226. if isinstance(val, list):
  227. # Don't need to convert tuples
  228. val = list(val)
  229. self._container[key.lower()] = [key] + val
  230. def copy(self):
  231. clone = type(self)()
  232. clone._copy_from(self)
  233. return clone
  234. def iteritems(self):
  235. """Iterate over all header lines, including duplicate ones."""
  236. for key in self:
  237. vals = self._container[key.lower()]
  238. for val in vals[1:]:
  239. yield vals[0], val
  240. def itermerged(self):
  241. """Iterate over all headers, merging duplicate ones together."""
  242. for key in self:
  243. val = self._container[key.lower()]
  244. yield val[0], ", ".join(val[1:])
  245. def items(self):
  246. return list(self.iteritems())
  247. @classmethod
  248. def from_httplib(cls, message): # Python 2
  249. """Read headers from a Python 2 httplib message object."""
  250. # python2.7 does not expose a proper API for exporting multiheaders
  251. # efficiently. This function re-reads raw lines from the message
  252. # object and extracts the multiheaders properly.
  253. obs_fold_continued_leaders = (" ", "\t")
  254. headers = []
  255. for line in message.headers:
  256. if line.startswith(obs_fold_continued_leaders):
  257. if not headers:
  258. # We received a header line that starts with OWS as described
  259. # in RFC-7230 S3.2.4. This indicates a multiline header, but
  260. # there exists no previous header to which we can attach it.
  261. raise InvalidHeader(
  262. "Header continuation with no previous header: %s" % line
  263. )
  264. else:
  265. key, value = headers[-1]
  266. headers[-1] = (key, value + " " + line.strip())
  267. continue
  268. key, value = line.split(":", 1)
  269. headers.append((key, value.strip()))
  270. return cls(headers)